<?php

namespace App\Services;

use App\Models\Address;
use App\Models\Area;
use App\Models\ElectricAlarmRecord;
use App\Models\ElectricCollector;
use App\Models\ElectricElectricity;
use App\Models\ElectricFeeLog;
use App\Models\ElectricPaymentOrder;
use App\Models\ElectricWater;
use App\Models\Users;
use Artisan;
use GatewayWorker\Lib\Db;
use Illuminate\Support\Facades\Log;
use phpDocumentor\Reflection\Types\Self_;
use Psy\Command\Command;
use Zxing\Qrcode\Decoder\ECB;

class NotifyService extends BaseService
{
    /**
     * 微信支付订单状态更新
     * @param $params
     * @return boolean
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     * @throws PDOException
     * @author Sdd
     */
    public static function update($params)
    {
        extract($params, null);
        /**
         * @var $order_no
         * @var $pay_price
         * @var $pay_no
         * @var $type
         *
         */
        // 检查订单支付状态
        $where = ['orderNo' => $order_no, 'status' => 1];
        $order = ElectricPaymentOrder::where($where)->count();
        if ($order == 0) {
            return false;
        }
        // 更新订单支付状态
        $data = [
            'pay_type' => $type,
            'pay_no' => $pay_no,
            'status' => 2,
            'pay_real' => $pay_price,
            'paymentTime' => date('Y-m-d H:i:s'),
        ];
        try {
            $result = ElectricPaymentOrder::where($where)->update($data);
            return true;
        } catch (\Exception $e) {
//            p($e->getMessage());
            return false;
        }


    }

    /**
     * 回调成功后处理方法
     * @param  $one_order
     * @return array|false
     * @throws Exception
     */
    public static function after_notify($one_order)
    {
        $bill_type_field = '';
        $bill_str = '';
        $user_model = new Users;
        $electric_model = new ElectricElectricity();
        $water_model = new ElectricWater();
        $owner = $user_model->find($one_order['user_id']);
        if (empty($owner)) {
            return false;
        }
        $user_id = $owner['id'];
        $code = '';
        switch ($one_order['feeType']) {
            case 1:
                $bill_type_field = 'electricity';
                $bill_str = '电费';
                $code = $electric_model->where(['id' => $owner['electric_id']])->value('code');
                break;
            case 2:
                $bill_type_field = 'water';
                $bill_str = '水费';
                $code = $water_model->where(['id' => $owner['water_id']])->value('code');
                break;
            case 3:
                $bill_type_field = 'property';
                $bill_str = '物业费';
                $code = $owner['room_number'];
                break;
        }
        \Illuminate\Support\Facades\DB::beginTransaction();

        try {
            $str1 = "{$bill_type_field}_bill_balance";
            $balance = $owner[$str1];
            $before_balance = $owner->$str1;
            $after_balance = $before_balance + $one_order['paymentMoney'];
            $bool = $owner->increment($str1, $one_order['paymentMoney']);
            self::insertFeeLog($user_id, $one_order, $before_balance, $after_balance);
            $alarm_where = ['user_id' => $owner['id'], 'code' => $code, 'alarm_type' => 2, 'is_failure' => 1];
            ElectricAlarmRecord::where($alarm_where)->delete();//销毁过期余额报警
            if ($one_order['feeType'] == 1 && $after_balance > 0) {
                self::device_handle($owner['electric_id'], 2);
            }
            \Illuminate\Support\Facades\DB::commit();
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\DB::rollback();
        }

        return ['one_order' => $one_order, 'bill_str' => $bill_str, 'after_balance' => $after_balance, 'owner' => $owner];
    }

    /**
     * 2021/3/18--16:22
     * @effect:操作设备
     * @param $electric_id
     * @param $rty
     * @param ElectricElectricity $electric_model
     * @param ElectricCollector $collector_model
     * @author:苏冬冬
     * @QQ:1299273928
     * @method:device_handle
     */
    public static function device_handle($electric_id, $rty)
    {
        $electric_model = new ElectricElectricity;
        $collector_model = new ElectricCollector;
        $electric = $electric_model->selectRaw('id,collect_id,tableAddress,is_close,is_protect')->find($electric_id);
        $collector = $collector_model->selectRaw('code')->find($electric['collect_id']);
        switch ($rty) {
            case 1://欠费拉闸
                if ($electric['is_protect'] == 2 && $electric['is_close'] == 1) {//如果不处于保电状态，且未合闸状态
                    $arr = ['electric_code' => $electric['tableAddress'], 'handle' => 'off', 'device_type' => '1', 'collect_id' => $collector['code']];
                    $result = Artisan::call('operating_equipment', $arr);
                    $electric->save(['is_close' => 2]);
                }
                break;
            case 2://缴费合闸
                if ($electric['is_close'] == 2) {//如果处于拉闸状态
                    $arr1 = ['electric_code' => $electric['tableAddress'], 'handle' => 'on', 'device_type' => '1', 'collect_id' => $collector['code']];
                    $result = Artisan::call('operating_equipment', $arr1);
                    $electric->save(['is_close' => 1]);
                }
                break;
        }

    }

    /**
     * 更新订单后操作
     * @param $param
     */
    public static function update_after($param): void
    {
        extract($param, null);
        /**
         * @var $one_order |订单
         * @var $bill_str |费用类型
         * @var $after_balance |支付后余额
         * @var $owner |业主信息
         */
        try {
            self::unifiedPaymentSend($one_order, $bill_str, $after_balance, $owner);
        } catch (\Exception $e) {
            Log::channel("wechat_split")->error('Pay notify', [$e->getMessage()]);
        }

    }

    /**
     * 统一发送信息，
     * @param $one_order
     * @param $bill_str
     * @param $balance
     * @param $owner
     * @throws InvalidResponseException
     * @throws PDOException
     * @throws LocalCacheException
     * @throws Exception
     */
    public static function unifiedPaymentSend($one_order, $bill_str, $balance, $owner): void
    {
        $name = $owner['username'];
        $user_id = $owner['id'];
        $notice_name = "{$name}缴费通知";
        $str = "恭喜{$name}缴费成功，缴费金额{$one_order['paymentMoney']}";
        $options = [
            'notice_name' => $notice_name,
            'notice_cate' => 2,
            'notice_author' => 'admin',
            'notice_content' => $str,
            'user_id' => $user_id,
            'agent_id' => 0
        ];
        $bool1 = self::send_notice($options);
        /**
         * 发送短息，插入短信记录
         */
        $options1 = [
            'user_id' => $user_id,
            'username' => $name,
            'mobile' => $owner['mobile'],
            'type' => 6,//短信类型:1,电费告警；2，其他；3，跳闸告警；4，预存、补助、退费；5，月费用提醒，6，缴费成功
            'content' => $str
        ];
        $bool2 = self::send_log($options1);
        $province = Db::name('sys_region')->whereIn('id', [$owner['province'], $owner['city'], $owner['area']])->column('name');
        $address = implode(',', $province);
        $community = Db::name('electric_community')->where(['id' => $owner['community']])->value('name');
        $community_area = Db::name('electric_community_area')->where(['id' => $owner['community']])->value('area_name');
        $full_address = $address . $community . $community_area . $owner['room_number'];
        switch ($one_order['device_type']) {

            case 2://公众号
            case 3://单独支付页面
                /**
                 * 微信公众号模板消息
                 */
                $openid = Db::name('wechat_fans')->where(['id' => $owner['wxchat_id']])->value('openid');
                if ($openid != '') {
                    $options = [
                        'user_name' => $name,
                        'full_address' => $full_address,
                        'amount' => $one_order['paymentMoney'],
                        'balance' => $balance,
                        'number' => $owner['elc_code'],
                        'openid' => $openid,
                    ];
                    (new SendPaymentSuccess())->doWechatSend($options);
                }
                break;
            case 1://小程序
                /**
                 * 微信小程序订阅消息
                 */
                $openid = Db::name('wechat_fans')->where(['id' => $owner['wechat_id']])->value('openid');
                if ($openid != '') {
                    $options = [
                        'bill_str' => $bill_str,
                        'orderNo' => $one_order['orderNo'],
                        'money' => $one_order['paymentMoney'],
                        'user_name' => $name,
                        'openid' => $openid
                    ];

                    (new SendPaymentSuccess)->doAppletsSend($options);
                }

                break;
        }
    }

    /**
     * 插入消费记录
     * @param $user_id
     * @param $one_order
     * @param $before_balance
     * @param $after_balance
     */
    public static function insertFeeLog($user_id, $one_order, $before_balance, $after_balance): void
    {
        $data = [
            'owner_id' => $user_id,
            'order_num' => $one_order['orderNo'],
            'pay_type' => $one_order['pay_type'],
            'type' => $one_order['type'],
            'before_balance' => $before_balance,
            'after_balance' => $after_balance,
            'bill_balance' => $one_order['paymentMoney'],
        ];
        ElectricFeeLog::create($data);
    }
}
